package com.xxh.market.controller;


import com.xxh.market.dao.BookTypeDao;
import com.xxh.market.dao.UserDao;
import com.xxh.market.dao.impl.BookTypeDaoImpl;
import com.xxh.market.dao.impl.UserDaoImpl;
import com.xxh.market.entity.Booktype;
import com.xxh.market.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;


//设置访问路径
@WebServlet(urlPatterns = "/user/*")
public class UserServlet extends HttpServlet {
    UserDao userDao=new UserDaoImpl();
    BookTypeDao bookTypeDao=new BookTypeDaoImpl();

    //处理get请求（浏览器请求，超链接，转发，重定向）
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理登录请求
        String pathInfo = req.getPathInfo();
        // 1 登录请求
        if(pathInfo.equals("/login")){
            //登录请求
            //请求处理
            String username = req.getParameter("username");
            String password = req.getParameter("password");

            System.out.println("username="+username+"password:"+password);
            User user = userDao.login(username, password);
            if(user!=null){
                HttpSession session = req.getSession();
                session.setAttribute("userDetail",user);
                List<Booktype>booktypeList=bookTypeDao.getAllTypes();
                session.setAttribute("bookTpes",booktypeList);
                //跳转到书籍的controller
                resp.sendRedirect(req.getContextPath()+"/book/index");

            }else {
                //重定向到登录页
                //req.getContextPath()获取web项目访问路径
                resp.sendRedirect(req.getContextPath()+"/login.jsp?info=1");
            }
        }
    }

    //处理post请求
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
